
from aaa import models

def get_rights_tree():
    pid_list = [i['pid'] for i in list(models.Permission.objects.filter(pid__isnull=False).values('pid').distinct())]
    x = models.Permission.objects.all().values('id', 'authName', 'url', 'pid_id', 'level')
    #一级二级权限
    fir_sen_dict = {}
    '''{
        8: {
            'children': [{
                'id': 3,
                'authName': '角色列表',
                'url': '/roles/',
                'pid_id': 8,
                'level': '1',
                'children': []
            }, {
                'id': 6,
                'authName': '权限列表',
                'url': '/rights/',
                'pid_id': 8,
                'level': '1',
                'children': []
            }],
            'id': 8,
            'authName': '权限管理',
            'url': '/rights/'
        },
        7: {
            'children': [{
                'id': 4,
                'authName': '用户列表',
                'url': '/users/',
                'pid_id': 7,
                'level': '1',
                'children': []
            }],
            'id': 7,
            'authName': '用户管理',
            'url': '/users/'
        }
    }'''

    #三级权限
    third_list = []
    '''[{'id': 5, 'authName': '添加客户', 'url': '/users/add/', 'pid_id': 4, 'level': '2'}, 
        {'id': 9, 'authName': '修改客户', 'url': '/users/edit/', 'pid_id': 4, 'level': '2'},
        {'id': 10, 'authName': '添加角色', 'url': '/roles/add/', 'pid_id': 3, 'level': '2'},
        {'id': 11, 'authName': '修改角色', 'url': '/roles/edit/', 'pid_id': 3, 'level': '2'}]
    '''
    for item in x:
        id = item['id']
        authName = item['authName']
        url = item['url']
        pid = item['pid_id']
        level = item['level']
        if pid:
            if level == '2':
                third_list.append(item)
                continue
            #二级权限设置children
            item['children'] = []
            if pid in fir_sen_dict:
                fir_sen_dict[pid]['children'].append(item)
            else:
                fir_sen_dict[pid] = {'children':[item]}
        else:
            #过滤掉首页
            if id == 1:
                continue
            fir_sen_dict[id]['id'] = id
            fir_sen_dict[id]['authName'] = authName
            fir_sen_dict[id]['url'] = url

    #一级二级权限改成列表，减少后边循环次数
    fir_sen_list = []
    for item in fir_sen_dict:
        fir_sen_list.append(fir_sen_dict[item])
    print('1',fir_sen_dict)
    print('third_list',third_list)

    for row in fir_sen_list:
        for sencond in row['children']:
            for item in third_list:
                if sencond['id'] == item['pid_id']:
                    sencond['children'].append(item)
    return fir_sen_list
